<template>
  <div class="caseManage">
    <el-tabs v-model="activeName" type="card" class="elTabs">
      <el-tab-pane name="first">
        <div slot="label" class="pageHeader">用户管理</div>
      </el-tab-pane>
    </el-tabs>
    <!--用户数据-->
    <div class="container">
      <div class="searchBar" v-show="showSearch">
        <div class="searchForm">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item label="用户名称:" prop="userName">
              <el-input
                class="input"
                v-model.trim="queryParams.nickName"
                placeholder="请输入用户名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="登录账号:" prop="role">
              <el-input
                class="input"
                v-model.trim="queryParams.userName"
                placeholder="请输入登录账号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="searchButtons">
          <el-button @click.native="handleQuery" class="searchButton"
            >搜索</el-button
          >
          <el-button @click.native="resetQuery" class="resetButton"
            >重置</el-button
          >
        </div>
      </div>
      <div class="addDeleteBar">
        <el-button
          @click.native="handleAdd"
          class="addButton"
          v-hasPermi="['system:user:add']"
          ><span class="plus">+</span>新增
        </el-button>
        <el-button
          @click.native="handleDelete"
          :class="!multiple ? 'deleteButton' : 'allDeleteButton'"
          icon="el-icon-delete"
          :disabled="multiple"
          v-hasPermi="['system:user:remove']"
          >批量删除</el-button
        >

        <el-button
          class="addButton"
          icon="el-icon-download"
          @click.native="handleImport"
          v-hasPermi="['system:user:import']"
          >导入</el-button
        >
        <el-button
          class="addButton"
          icon="el-icon-upload2"
          @click.native="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </div>
      <!-- 表单选择清空 -->
      <div class="tableSelectArea">
        <div>
          <div class="iconInfo el-icon-info"></div>
          <span class="infoText">已选择</span>
          <span class="infoText infoActive" v-text="selectedNum"></span>
          <span class="infoText">项</span>
          <span class="infoButton" @click="clearSelect">清空</span>
        </div>
        <div>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </div>
      </div>
      <div class="table">
        <el-table
          v-loading="loading"
          style="width: 100%"
          ref="multipleTable"
          class="tableArea"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            width="50"
            type="index"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="用户名称"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="登录账号"
            width="100"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            label="所属部门"
            align="center"
            key="deptName"
            prop="dept.deptName"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
          label="角色列表"
          align="center"
          key="phonenumber"
          prop="phonenumber"
          v-if="columns[4].visible"
        /> -->
          <el-table-column
            label="是否停用"
            align="center"
            key="status"
            v-if="columns[5].visible"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="300" fixed="right">
            <template slot-scope="scope">
              <div class="tableButtonArea">
                <el-button
                  type="text"
                  class="operationButton"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:user:edit']"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  class="operationButton"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
                  >删除</el-button
                >
                <el-button
                  type="text"
                  class="operationButton"
                  v-hasPermi="['system:user:resetPwd']"
                  @click="handleResetPwd(scope.row)"
                  >重置密码</el-button
                >
                <el-button
                  type="text"
                  class="operationButton"
                  v-hasPermi="['system:user:edit']"
                  @click="handleAuthRole(scope.row)"
                  >分配角色</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="tableFooter">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <UserModal
      ref="userModal"
      :modalType.sync="modalType"
      :userId="rowId"
      @fatherMethod="fatherMethod"
    ></UserModal>
    <UserUpload ref="userUpload"> </UserUpload>
    <TransferModal :id="userId" :modalDeptId="modalDeptId"></TransferModal>
  </div>
</template>

<script>
import {
  listUser,
  resetUserPwd,
  changeUserStatus,
  delUser,
} from "@/api/system/user";
import { fatherMethod } from "../../../utils/commonMethods";
import {
  PAGESIZE,
  PAGENUM,
  USEREXPORTURL,
  MODALTYPE,
  PASSWORD,
} from "../../../utils/variable";
// import Table from "@/components/Table/index.vue"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UserModal from "./components/userModal";
import UserUpload from "./components/userUpload";
import TransferModal from "./components/transferModal.vue";
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { UserModal, UserUpload, TransferModal },
  data() {
    return {
      modalDeptId: "",
      userId: "",
      password: PASSWORD,
      rowId: "",
      //模态框类型
      modalType: "",
      //列表选中数量
      selectedNum: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: "",
      // 默认密码
      initPassword: "",
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      activeName: "first",
      // 查询参数
      queryParams: {
        pageNum: PAGENUM,
        pageSize: PAGESIZE,
        userName: "",
        role: "",
        department: "",
        roleIds: "",
        // deptId: '',
      },
      // 列信息
      // TODO:这个代码的意义是什么？设定死了？
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `登录账号`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
  },
  methods: {
    fatherMethod,
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 筛选节点
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.label.indexOf(value) !== -1;
    // },
    // 节点单击事件
    // handleNodeClick(data) {
    //   this.queryParams.deptId = data.id;
    //   this.handleQuery();
    // },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    //清空列表选择
    clearSelect() {
      this.$refs.multipleTable.clearSelection();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: "",
        deptId: "",
        userName: "",
        nickName: "",
        password: "",
        phonenumber: "",
        email: "",
        sex: "",
        status: "0",
        remark: "",
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = PAGENUM;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      // this.resetForm("queryForm");
      this.queryParams.deptId = "";
      this.queryParams.pageNum = PAGENUM;
      this.queryParams.pageSize = PAGESIZE;
      this.queryParams.userName = "";
      (this.queryParams.nickName = ""), (this.queryParams.role = "");
      this.queryParams.department = "";
      // this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedNum = selection.length;
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.modalType = MODALTYPE["新增"];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.modalType = MODALTYPE["修改"];
      this.rowId = row.userId || this.ids;
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$modal
        .confirm("确定重置该用户密码？重置后默认密码为123456", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonClass: "searchButton",
          cancelButtonClass: "resetButton",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        })
        .then(() => {
          resetUserPwd(row.userId, PASSWORD).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + PASSWORD);
          });
        })
        .catch(() => {});
      // this.$prompt(
      //   '请输入"' + row.nickName + '"的新密码，此操作将修改用户密码，是否确认',
      //   "管理员重置密码",
      //   {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     confirmButtonClass: "searchButton",
      //     cancelButtonClass: "resetButton",
      //     closeOnClickModal: false,
      //     inputPattern: /^.{5,20}$/,
      //     inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      //   }
      // )
      //   .then(({ value }) => {
      //     resetUserPwd(row.userId, value).then((response) => {
      //       this.$modal.msgSuccess("修改成功，新密码是：" + value);
      //     });
      //   })
      //   .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      this.userId = row.userId;

      this.modalDeptId = row.deptId;
      // this.$router.push("/system/user-auth/role/" + userId);
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      let num = this.selectedNum;
      if (row.userId) {
        num = 1;
      }
      this.$modal
        .confirm("是否确认删除" + num + "条用户数据")
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // TODO：这个路径是
      this.download(
        USEREXPORTURL,
        {
          ...this.queryParams,
        },
        `导出用户_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      // TODO：模态框的打开和关闭是通过直接操作子组件的方式实现的吗？
      this.$refs.userUpload.upload.title = "用户导入";
      this.$refs.userUpload.upload.open = true;
    },
  },
};
</script>
<style lang='scss' scoped >
@import "../../../assets/styles/variables.scss";
@import "@/assets/styles/dialog.scss"; //模态框样式
.caseManage {
  height: 100%;
  .tableFooter {
    text-align: right;
    justify-content: flex-end;
    // margin-top: 25px;
    margin-right: 35px;
    // width: 100%;
    ::v-deep .btn-prev {
      color: #d4d3d3 !important;
      background-color: #fff;
      border: 1px solid #d4d3d3;
    }
    ::v-deep .btn-next {
      color: #d4d3d3 !important;
      background-color: #fff;
      border: 1px solid #d4d3d3;
    }
    ::v-deep .el-pager li {
      background-color: #fff;
      border: 1px solid #d4d3d3;
      font-size: 12px;
      font-family: $font-family;
      font-weight: 400;
      color: #5a5b5d;
    }
  }
}
::v-deep.el-upload {
  width: 200px !important;
  height: 200px;
}
.input {
  width: 150px;
}
.searchButton {
  width: 81px;
  border: 0px;
  height: 39px;
  background: #598af9 !important;
  border-radius: 3px;
  font-size: 16px;
  margin-right: 10px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  letter-spacing: 0;
  color: #fefbfb;
  line-height: 10px;
  letter-spacing: 2px;
}
.resetButton {
  border: 1px solid #2985f7;
  border-radius: 2px;
  width: 81px;
  height: 39px;
  background: #fff;
  font-size: 16px;
  font-family: Microsoft YaHei;
  line-height: 9px;
  font-weight: bold;
  letter-spacing: 0;
  color: #598af9;
  letter-spacing: 2px;
}

.el-tabs--card > .el-tabs__header .el-tabs__nav {
  border: 0px;
}
::v-deep .el-tabs--card .el-tabs__header {
  background-color: #e4e7ed;
}
::v-deep.el-tabs--card .el-tabs__header .el-tabs__item {
  border-radius: 10px solid black;
  background-color: #fff;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #053ef6;
  line-height: 48px;
  margin-top: 0;
}
.el-tabs--card {
  margin-left: 10px;
  border: 0px !important;
}
</style>